import woman from '@/assets/woman.png';
import { Affix, Button, Flex, Space } from 'antd';
import { useIntl, useLocation } from 'umi';

import CopyrightFooter from '@/components/CopyrightFooter';
import TopBar from '@/components/TopBar';
import { donwLoadApp, donwLoadGoogle, getNewUrl } from '@/utils';
import 'dayjs/locale/zh-tw';
import { useEffect, useRef, useState } from 'react';
import { Link, Outlet, useModel } from 'umi';
import './index.less';

import ContactModal from '@/components/ContactModal';
import FloatButtons from '@/components/FloatButton';

import code from '@/assets/app_code.png';
import app from '@/assets/footer_app.png';
import close from '@/assets/footer_close.png';

import w_close from '@/assets/close.png';

import google from '@/assets/footer_google.png';
import iphone from '@/assets/footer_iphoe.png';
import dayjs from 'dayjs';
import CountUp from 'react-countup';
let duration1: any = dayjs().add(60, 'seconds');

export default function Layout() {
  const list = [
    {
      navTitle: 'home.cash_price',
      navList: [
        {
          url: '/cashback#mode',
          word: 'home.cash_mode',
        },
        {
          url: '/cashback#way',
          word: 'home.how_get_cash',
        },
        {
          url: '/cashback#activity',
          word: 'home.cash_activity',
        },
      ],
    },
    // {
    //   navTitle: 'home.credit_evaluation',
    //   navList: [
    //     {
    //       url: '/credit#what',
    //       word: 'home.credit_scroe',
    //     },
    //     {
    //       url: '/credit#need',
    //       word: 'home.why',
    //     },
    //     {
    //       url: '/credit#check',
    //       word: 'home.investigate_loaner',
    //     },
    //     {
    //       url: '/credit#report',
    //       word: 'home.credit_report',
    //     },
    //   ],
    // },
    {
      navTitle: 'home.common_problem',
      navList: [
        {
          url: '/problem?id=1',
          word: 'home.resign_login',
        },
        {
          url: '/problem?id=2',
          word: 'home.write_data',
        },
        {
          url: '/problem?id=3',
          word: 'home.flow',
        },
        {
          url: '/problem?id=4',
          word: 'home.show_more',
        },
      ],
    },
    {
      navTitle: 'home.about_us',
      navList: [
        {
          url: '/about',
          word: 'home.company_introduce',
        },
        {
          url: '/work',
          word: 'home.work_chance',
        },
        {
          url: '/contact',
          word: 'home.concat_us',
        },
      ],
    },
    {
      navTitle: 'home.company_news',
      navList: [
        {
          url: '/news?index=1',
          word: 'home.news_flash',
        },
        {
          url: '/news?index=2',
          word: 'home.investment_financing',
        },
        {
          url: '/news?index=3',
          word: 'home.finance_news',
        },
        // {
        //   url: '/news?index=4',
        //   word: 'home.finance_news',
        // },
      ],
    },
  ];

  const router = useLocation();

  const [modalVisible, setModalVisible] = useState(false);
  const [show, setShow] = useState(true);
  const pathName = ['/', '/product', '/center', '/supplement', '/orderDetail', '/land'];
  const intl = useIntl();
  const isEn = intl.locale == 'en-US';
  const urlList = [
    'https://www.facebook.com/profile.php?id=61567323605473',
    'https://www.linkedin.com/company/xlend-limited/',
    'https://www.youtube.com/@XLENDLIMITED',
    'https://www.instagram.com/xlendhk/',
  ];
  const [webVisible, setWebVisible] = useState(false);
  const blueColorUrl = ['/MerchantDetail', '/comment'];
  const [visible, setVisible] = useState(false);
  const [appVisible, setAppVisible] = useState(false);
  const [className, setClassName] = useState<any>('');
  const { cookie: hasFirst, setCookie: setCookieFn } = useModel('userModel');

  const handleCookieVisible = () => {
    setVisible(false);
    localStorage.setItem('cookie', 'true');
    setCookieFn('ok');
  };
  const handleAppVisible = () => {
    setClassName(true);
    setTimeout(() => {
      setAppVisible(false);
      localStorage.setItem('app', 'true');
    }, 1000);
  };
  const duration = dayjs().add(30, 'seconds');
  const prompt = useRef<any>();

  const showApp = () => {
    prompt.current.prompt();
    // 等待用户对 prompt 进行操作
    // 如果用户从地址栏或其他浏览器组件安装了PWA，则以下代码将不起作用
    prompt.current.userChoice.then((choiceResult: any) => {
      if (choiceResult.outcome === 'accepted') {
        setWebVisible(false);
      } else {
        // 取消
        setWebVisible(false);
      }
      prompt.current = null;
      localStorage.setItem('donwload', 'true');
    });
  };

  useEffect(() => {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/sw.js').then(function () {});
    }
    if (!localStorage.getItem('donwload')) {
      window.addEventListener('beforeinstallprompt', (e) => {
        console.log('触发!');
        e.preventDefault();
        // 存放事件用于后续触发
        prompt.current = e;
        const timer1 = setInterval(() => {
          // 在页面呆60s 出现
          if (duration1 && dayjs().toString() >= duration1.toString()) {
            setWebVisible(true);
            duration1 = '';
            clearInterval(timer1);
          }
        }, 1000);
        // Chrome 67 及之前版本，会自动展现安装的 prompt
        // 为了版本统一及用户体验，我们禁止自动展现 prompt

        // 展现按钮
      });
    }
  }, []);
  useEffect(() => {
    if (!hasFirst) {
      setVisible(true);
    }
    if (!localStorage.getItem('app')) {
      const timer = setInterval(() => {
        // 在页面呆30s 出现
        if (dayjs().toString() == duration.toString()) {
          setAppVisible(true);
          clearInterval(timer);
        }
      }, 1000);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    // 用于隐藏预渲染打包的页面

    if (!window.location.href.includes('https') && process.env.NODE_ENV == 'production') {
      setShow(false);
    }
  }, []);

  const routerPathName = router.pathname.replace('/en', '') || '/';

  const name =
    routerPathName.split('/').length > 1 ? `/${routerPathName.split('/')[1]}` : routerPathName;

  const isBlue = blueColorUrl.includes(name);

  const serviceList = [
    { title: 'home.user_number', word: '+', value: 100 },
    { title: 'home.loan_number', word: intl.formatMessage({ id: 'home.pen1' }), value: 5000 },
    {
      title: 'home.loan_num',
      word: intl.formatMessage({ id: 'center.money_e' }),
      value: isEn ? 100 : 1,
    },
    {
      title: 'home.loan_back',
      word: intl.formatMessage({ id: 'center.money_e1' }),
      value: 5,
    },
  ];

  return (
    <div className="common_layout" style={{ paddingTop: hasFirst ? 0 : 56, opacity: show ? 1 : 0 }}>
      <FloatButtons />
      {!pathName.includes(name) ? (
        <Affix offsetTop={!hasFirst ? 56 : 0}>
          <div
            className={`topbg ${isBlue ? 'blue_bg' : ''}`}
            style={{
              boxShadow: isBlue ? 'none' : '0px 7px 4px 0px #0000000D',
              backgroundColor: isBlue ? 'rgb(18, 59, 164)' : '#fff',
            }}
          >
            <TopBar dark={!isBlue} style={{ padding: '12px 0' }} />
          </div>
        </Affix>
      ) : null}
      <div style={{ minHeight: '100vh' }}>
        <Outlet />
      </div>
      <div className="footer">
        {/* 左边背景 */}
        <div style={{ overflow: 'hidden', width: '100%', height: '100%', position: 'absolute' }}>
          <div className="footer_bg" />
        </div>

        <div className="common footer_content">
          <Flex justify="space-between">
            <Flex style={{ position: 'relative', zIndex: 11 }} gap={isEn ? 25 : 50}>
              {list.map((item) => {
                const { navTitle, navList } = item;
                return (
                  <Flex
                    style={{
                      flexDirection: 'column',
                      color: '#fff',
                    }}
                    gap={15}
                    key={navTitle}
                  >
                    <div className="footer_content_title">
                      {intl.formatMessage({ id: navTitle })}
                    </div>
                    {navList.map((item) => {
                      const { url, word } = item;
                      return (
                        <Link to={getNewUrl(url)} key={word}>
                          <span className="footer_content_word">
                            {intl.formatMessage({ id: word })}
                          </span>
                        </Link>
                      );
                    })}
                  </Flex>
                );
              })}
            </Flex>
            <div className="footer_people" style={{ top: isEn ? -62 : -84 }}>
              <img src={woman} height={340} />
            </div>
            <Flex
              style={{
                flexDirection: 'column',
                color: '#fff',
                textAlign: 'right',
              }}
              align="flex-end"
            >
              <div style={{ fontSize: 22, width: isEn ? 300 : 'auto' }}>
                {intl.formatMessage({ id: 'home.lend' })}
              </div>
              <div
                style={{
                  opacity: 0.8,
                  marginTop: 12,
                  lineHeight: '21px',
                  width: isEn ? 280 : 'auto',
                  marginLeft: 'auto',
                }}
              >
                {/* <div>{intl.formatMessage({ id: 'home.risk' })}</div> */}
                <div>{intl.formatMessage({ id: 'home.rational' })}</div>
              </div>

              <div style={{ fontSize: 18, marginTop: isEn ? 23 : 47 }}>
                {intl.formatMessage({ id: 'home.follow_us' })}
              </div>
              <Space size={14} style={{ marginTop: 15 }}>
                {urlList.map((item, index) => {
                  return (
                    <div className="footer_icon" key={item} style={{ cursor: 'pointer' }}>
                      <a href={item} target="_blank" rel="noreferrer">
                        <img width={40} src={require(`@/assets/f${index + 1}.png`)} />
                      </a>
                    </div>
                  );
                })}
              </Space>
            </Flex>
          </Flex>
          <div style={{ padding: '20px 0', position: 'relative', zIndex: 11 }}>
            <CopyrightFooter />
          </div>
          <div
            style={{
              lineHeight: '25px',
              paddingBottom: 15,
              color: 'rgba(255, 255, 255, 0.5)',
              textAlign: 'center',
            }}
          >
            <div style={{ fontSize: 12 }}>{intl.formatMessage({ id: 'home.provide' })}</div>
            <div style={{ fontSize: 12 }}>{intl.formatMessage({ id: 'home.over' })}</div>
          </div>
        </div>
      </div>
      {visible && (
        <div className="cookie">
          <Flex align="center" className="common" justify="space-between">
            <div style={{ fontSize: isEn ? 13 : 16 }}>
              {intl.formatMessage({ id: 'home.cookie' })}
            </div>
            <Flex gap={22} align="center">
              <div
                style={{ lineHeight: isEn ? '24px' : '28px' }}
                onClick={handleCookieVisible}
                className="cookie_btn"
              >
                {intl.formatMessage({ id: 'home.agrees' })}
              </div>
              <div
                style={{ lineHeight: isEn ? '24px' : '28px' }}
                onClick={handleCookieVisible}
                className="cookie_btn"
              >
                {intl.formatMessage({ id: 'home.reject' })}
              </div>
            </Flex>
          </Flex>
        </div>
      )}
      {/* 底部下载 */}
      {appVisible && (
        <div className={`${!className ? 'slide-up-animation' : 'slide-down-animation '} donwload`}>
          <div
            className="common"
            style={{ position: 'relative', display: 'flex', alignItems: 'center' }}
          >
            <div className="close" onClick={handleAppVisible}>
              <img src={close} width={30} height={30} />
            </div>
            <div style={{ marginTop: -38 }}>
              <img src={iphone} width={220} />
            </div>
            <div style={{ margin: '0 109px 0 40px' }}>
              <div style={{ fontSize: 22, fontWeight: 700, marginBottom: 12 }}>
                {intl.formatMessage({ id: 'home.footer_xlend' })}
              </div>

              <Flex gap={34}>
                {serviceList.map((item) => {
                  const { title, word, value } = item;
                  return (
                    <div key={title}>
                      <Flex gap={2} align="center" style={{ flexDirection: 'column' }}>
                        <Flex style={{ opacity: 0.8 }} gap={5} align="center">
                          <div style={{ fontWeight: 700, fontSize: 20, lineHeight: '23px' }}>
                            <CountUp separator="" end={value} />
                          </div>
                          <div style={{ fontSize: 16, lineHeight: '26px' }}> {word}</div>
                        </Flex>
                        <div style={{ color: '#fff', opacity: 0.5 }}>
                          {intl.formatMessage({ id: title })}
                        </div>
                      </Flex>
                    </div>
                  );
                })}
              </Flex>
            </div>
            <div>
              <div style={{ fontWeight: 700, marginBottom: 9 }}>
                {intl.formatMessage({ id: 'home.footer_scan' })}
              </div>
              <Flex gap={42}>
                <img src={code} width={70} height={70} />
                <div>
                  <div
                    style={{ cursor: 'pointer', marginBottom: 10 }}
                    onClick={() => {
                      donwLoadApp();
                    }}
                  >
                    <img width={100} src={app} />
                  </div>
                  <div
                    style={{ cursor: 'pointer' }}
                    onClick={() => {
                      donwLoadGoogle();
                    }}
                  >
                    <img width={100} src={google} />
                  </div>
                </div>
              </Flex>
            </div>
          </div>
        </div>
      )}
      {/* 安装应用 */}
      {webVisible && (
        <div className="window">
          <div>
            <div>{intl.formatMessage({ id: 'home.add_wob' })}</div>
            <div
              className="close"
              onClick={() => {
                setWebVisible(false);
                localStorage.setItem('donwload', 'true');
                prompt.current = null;
              }}
            >
              <img src={w_close} width={22} height={22} />
            </div>
            <Flex justify="flex-end" style={{ marginTop: 20 }}>
              <Button className="add-button" onClick={showApp} type="primary">
                {intl.formatMessage({ id: 'home.install' })}
              </Button>
            </Flex>
          </div>
        </div>
      )}
      <ContactModal
        visible={modalVisible}
        handleCancel={() => {
          setModalVisible(false);
        }}
      />
    </div>
  );
}
